package br.com.lp3.livraria.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.Criteria;

import br.com.lp3.livraria.util.HibernateUtil;

public abstract class GenericoDao<T> {

	private static EntityManager entityManager;
	
	public T buscarPorId(Long id) {
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		return (T) entityManager.find(getGenericType(), id);
	}

	public void salvar(T entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.persist(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}
	
	public void deletar(T entity) {
		
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.remove(entity);
			entityManager.getTransaction().commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		}
	}
	
	public void alterar(T entity) {
		try {
			entityManager = HibernateUtil.getInstancia().getEntityManager();
			entityManager.getTransaction().begin();
			entityManager.merge(entity);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			entityManager.getTransaction().rollback();

		} 
	}
	
	public List<T> buscartodos(){
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		Query query = entityManager.createQuery("FROM "+getGenericType().getSimpleName());
		return query.getResultList();
	}
	 
	public List<T> executaQuery(String hql,String... parametros){
		entityManager = HibernateUtil.getInstancia().getEntityManager();
		Query query = entityManager.createQuery(hql);
		
		int indiceParametro = 0;
		for (String parametro : parametros) {
		
			indiceParametro++;
			query.setParameter(indiceParametro, parametro);
			

		}
		
		return query.getResultList();
	}
	
	private Class getGenericType() {
		return (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
}
